package com.skyline.energy.executor;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import com.skyline.energy.cache.CacheManager;
import com.skyline.energy.dataaccess.jdbc.JdbcDataAccessor;
import com.skyline.energy.exception.DaoGenerateException;
import com.skyline.energy.executor.impl.CacheExecutor;
import com.skyline.energy.executor.impl.SqlExecutor;

public final class ExecutorFactory {
	private static final int CACHE_INIT_SIZE = 256;
	private static final Map<Method, DataAccessExecutor> EXECUTOR_CACHE = new HashMap<Method, DataAccessExecutor>(
			CACHE_INIT_SIZE);

	private ExecutorFactory() {
	}

	public static DataAccessExecutor getExecutor(CacheManager cacheManager, JdbcDataAccessor dataAccessor, Method method)
			throws DaoGenerateException {
		DataAccessExecutor executor = EXECUTOR_CACHE.get(method);

		if (executor == null) {
			CacheExecutor cacheExecutor = createCacheExecutor(cacheManager, method);
			SqlExecutor sqlExecutor = createSqlExecutor(dataAccessor, method);
			
			cacheExecutor.setDataAccessExecutor(sqlExecutor);
			executor = cacheExecutor;
			
			EXECUTOR_CACHE.put(method, executor);
		}

		return executor;

	}

	private static CacheExecutor createCacheExecutor(CacheManager cacheManager, Method method)
			throws DaoGenerateException {
		CacheExecutor executor = new CacheExecutor(cacheManager, method);

		return executor;
	}

	private static SqlExecutor createSqlExecutor(JdbcDataAccessor dataAccessor, Method method)
			throws DaoGenerateException {
		SqlExecutor executor = new SqlExecutor(dataAccessor, method);

		return executor;
	}

}
